/**
 * @file child.c
 * @brief
 * @author h0rr0rr_drag0n <h0rr0rr_drag0n@vindekapets.ru
 * @date 19 Июль 2010 12:27:41
 *
 * Check for child flag and execute proper funcs
 */

#include <errno.h>
#include <signal.h>
#include <syslog.h>
#include <string.h>
#include <sys/wait.h>

extern volatile int child_flag;

/**
 * @brief Actions when SIGCHLD comes
 */
int catch_sigchld() {
    sigset_t blockset;

    if (sigemptyset(&blockset)) {
        syslog(LOG_ERR,
                "Error: sigemptyset(): %s", strerror(errno));
        return 1;
    }
    if (sigaddset(&blockset, SIGCHLD)) {
        syslog(LOG_ERR,
                "Error: sigaddset(), %s", strerror(errno));
        return 1;
    }
    if (sigprocmask(SIG_BLOCK, &blockset, NULL)) {
        syslog(LOG_ERR,
                "Error: sigprocmask(): %s", strerror(errno));
        return 1;
    }
    child_flag = 0;
    while (waitpid(-1, NULL, WNOHANG) > 0) {}
    if (sigprocmask(SIG_UNBLOCK, &blockset, NULL)) {
        syslog(LOG_ERR,
                "Error: sigprocmask(): %s", strerror(errno));
        return 1;
    }

    return 0;
}

/**
 * @brief Check for SIGCHLD
 */
int check_sigchld() {
    if (child_flag) {
        if (catch_sigchld()) {
            return 1;
        }
    }

    return 0;
}

